package domain;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "work_post")
public class WorkPost extends PersistentEntity {
	@OneToOne(fetch=FetchType.EAGER)
	private User creator;
	
	private String title;
	private String hours;
	private Date start;
	@Column(length=10000)
	private String description;
	
	@ManyToMany
	private List<User> usersInvited;
	
	//hibernate
	public WorkPost() {
	}
	
	public WorkPost(User creator, String title, Date start, String hours, String description) {
		this.creator = creator;
		this.setTitle(title);
		this.setHours(hours);
		this.setStart(start);
		this.description = description.replace("\n", "<br />");
		this.usersInvited = new ArrayList<User>();
	}

	public User getCreator() {
		return creator;
	}

	public void setCreator(User creator) {
		this.creator = creator;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public void setUsersInvited(List<User> usersInvited) {
		if (usersInvited != null) {
			this.usersInvited = usersInvited;
		}
	}
	
	public void addSearchProfiles(List<SearchResultList> profiles) {
		if (profiles != null) {
			for (SearchResultList profile: profiles) {
				for (SearchResultItem item: profile.getResults()) {
					User u = item.getUser();
					if (!usersInvited.contains(u)) {
						this.usersInvited.add(u);
					}
				}
			}
		}
	}

	public List<User> getUsersInvited() {
		return usersInvited;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		WorkPost other = (WorkPost) obj;
		return other.getId() == this.getId();
	}

	@Override
	public int hashCode() {
		return this.getId();
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setHours(String hours) {
		this.hours = hours;
	}

	public String getHours() {
		return hours;
	}

	public void setStart(Date start) {
		this.start = start;
	}

	public Date getStart() {
		return start;
	}
	
	public String getFormattedStart() {
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy - HH:mm");
		return df.format(this.getStart());
	}
	
	@Override
	public String toString() {
		return "<h2>" + this.getTitle() + "</h2>" +
				"<b>Creado por: </b>" + this.getCreator().getName() + " " + this.getCreator().getLastName() + "</li><br />" +
				"<b>Tipo de puesto: </b>" + this.getHours() + "</li><br />" +
				"<b>Fecha de inicio: </b>" + this.getFormattedStart() + "</li><br />" +
				"<p>" +
				this.getDescription() +
				"</p>";
	}
}